package cn.miao.photoprinter.activity;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.miao.photoprinter.R;
import cn.miao.photoprinter.adapter.MenuAdapter;
import cn.miao.photoprinter.adapter.MyImageAdapter;
import cn.miao.photoprinter.anim.RotateAnimation;
import cn.miao.photoprinter.anim.RotateAnimation.InterpolatedTimeListener;
import cn.miao.photoprinter.database.DatabaseHelper;
import cn.miao.photoprinter.entity.FavPhoto;
import cn.miao.photoprinter.entity.MenuItem;
import cn.miao.photoprinter.entity.PhotoCheckItem;
import cn.miao.photoprinter.util.DialogUtil;
import cn.miao.photoprinter.util.MMAlert;
import cn.miao.photoprinter.util.ToastUtil;
import cn.miao.photoprinter.util.Util;
import cn.miao.photoprinter.view.DragLayout;
import cn.miao.photoprinter.view.DragLayout.DragListener;

import com.meg7.widget.CircleImageView;
import com.nineoldandroids.view.ViewHelper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import dev.dworks.libs.astickyheader.SimpleSectionedGridAdapter;
import dev.dworks.libs.astickyheader.SimpleSectionedGridAdapter.Section;

public class MainActivity extends CacheActivity {

	private DragLayout dragLayout;
	private GridView photoGridView;
	private ArrayList<Section> sections = new ArrayList<Section>();
	private MyImageAdapter adapter;

	private ListView lvMenu;
	private TextView tv_noimg, iv_info;
	private ImageView iv_icon, iv_cam, iv_select;
	private TextView tvCartCnt;
	CircleImageView iv_bottom;
	private static Handler handler;

	private String[] mHeaderNames = {};
	private Integer[] mHeaderPositions = {};

	ImageButton btCart;

	private static final int LOADOK = 10001;
	private static final int LOADFAIL = 10002;
	private static final int UPDATECART = 10003;

	private final int CAM = 20001;
	private final int SHOPPINGORDER = 20002;

	TextView tv_login;
	TextView tv_setting;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
		}
		SystemBarTintManager tintManager = new SystemBarTintManager(this);
		tintManager.setStatusBarTintEnabled(true);
		tintManager.setStatusBarTintResource(R.color.title_bar);
		
		handler = new MyHandler(this);
		Util.initImageLoader(this);
		initDragLayout();
		initMainView();
		initControls();
		startRefreshPhotos();
	}
	
	@TargetApi(19) 
	private void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	private void startRefreshPhotos() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(300);
					loadImage();
				} catch (Exception e) {
				}
			}
		}).start();
	}

	private void initDragLayout() {
		dragLayout = (DragLayout) findViewById(R.id.draglayout);
		dragLayout.setDragListener(new DragListener() {
			@Override
			public void onOpen() {
				lvMenu.smoothScrollToPosition(new Random().nextInt(30));
			}

			@Override
			public void onClose() {
			}

			@Override
			public void onDrag(float percent) {
				animate(percent);
			}
		});
	}

	private void animate(float percent) {
		ViewGroup vg_left = dragLayout.getVg_left();
		ViewGroup vg_main = dragLayout.getVg_main();

		float f1 = 1 - percent * 0.3f;
		ViewHelper.setScaleX(vg_main, f1);
		ViewHelper.setScaleY(vg_main, f1);
		ViewHelper.setTranslationX(vg_left, -vg_left.getWidth() / 2.2f
				+ vg_left.getWidth() / 2.2f * percent);
		ViewHelper.setScaleX(vg_left, 0.5f + 0.5f * percent);
		ViewHelper.setScaleY(vg_left, 0.5f + 0.5f * percent);
		ViewHelper.setAlpha(vg_left, percent);
		ViewHelper.setAlpha(iv_icon, 1 - percent);

		int color = (Integer) Util.evaluate(percent,
				Color.parseColor("#ff000000"), Color.parseColor("#00000000"));
		dragLayout.getBackground().setColorFilter(color, Mode.SRC_OVER);
	}

	private void initControls() {
		photoGridView = (GridView) findViewById(R.id.gv_img);
		adapter = new MyImageAdapter(this);
		// loadImage();
		for (int i = 0; i < mHeaderPositions.length; i++) {
			sections.add(new Section(mHeaderPositions[i], mHeaderNames[i]));
		}
		SimpleSectionedGridAdapter simpleSectionedGridAdapter = new SimpleSectionedGridAdapter(
				this, adapter, R.layout.grid_item_header, R.id.header_layout,
				R.id.header);

		simpleSectionedGridAdapter.setGridView(photoGridView);
		simpleSectionedGridAdapter
				.setSections(sections.toArray(new Section[0]));
		photoGridView.setAdapter(simpleSectionedGridAdapter);
		photoGridView.setOnItemClickListener(new OnItemClickListener() {
			@SuppressLint("NewApi")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				SimpleSectionedGridAdapter simpleAdapter = (SimpleSectionedGridAdapter) parent
						.getAdapter();
				int realPosition = simpleAdapter
						.sectionedPositionToPosition(position);
				Intent intent = new Intent(MainActivity.this,
						ImageActivity.class);
				intent.putExtra("path", adapter.getItem(realPosition).getPath());
				// startActivity(intent);
				CheckBox checkBox = (CheckBox) view.findViewById(R.id.ck_item);
				if (checkBox.isChecked()) {
					checkBox.setChecked(false);
					adapter.getItem(realPosition).setCheck(false);
				} else {
					checkBox.setChecked(true);
					adapter.getItem(realPosition).setCheck(true);
				}
			}
		});
		photoGridView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				SimpleSectionedGridAdapter simpleAdapter = (SimpleSectionedGridAdapter) parent
						.getAdapter();
				final int realPosition = simpleAdapter
						.sectionedPositionToPosition(position);
				// ToastUtil.showTips(MainActivity.this, R.drawable.tips_error,
				// realPosition + "," + position);
				
				MMAlert.showAlert(
						MainActivity.this,
						getString(R.string.select_menu),
						MainActivity.this.getResources().getStringArray(
								R.array.select_opts), null,
						new MMAlert.OnAlertSelectId() {

							@Override
							public void onClick(int whichButton) {
								switch (whichButton) {
								case 0: {
									Intent intent = new Intent(
											MainActivity.this,
											PhotoViewActivity.class);
									intent.putExtra("imagepath", adapter
											.getItem(realPosition).getPath());
									startActivity(intent);
									break;
								}
								case 1:
									String path = adapter.getItem(
											realPosition).getPath();
									FavPhoto favPhoto = new FavPhoto();
									favPhoto.setPath(path);
									favPhoto.setDate(getSectionName(realPosition));
									new DatabaseHelper(MainActivity.this).insertFavPhoto(favPhoto);
									break;
								case 2: {
									Intent share = new Intent(
											Intent.ACTION_SEND); // 启动分享发送的属性
									File file = new File(adapter.getItem(
											realPosition).getPath());
									share.putExtra(Intent.EXTRA_STREAM,
											Uri.fromFile(file));
									share.setType("image/jpeg");
									startActivity(Intent.createChooser(share,
											"选择分享"));// 目标应用选择对话框的标题
									break;
								}
								default:
									break;
								}
							}
						});
				return true;
			}
		});
	}
	
	private String getSectionName(int position) {
		for (int idx = 0; idx < mHeaderPositions.length; idx++) {
			if (position >= mHeaderPositions[idx]) {
				if (idx < mHeaderPositions.length
					&& position < mHeaderPositions[idx + 1]) {
					return mHeaderNames[idx];
				}
			}
		}
		return "";
	}

	private void refreshPhotos() {
		if (sections.size() > 0) {
			sections.clear();
		}
		for (int i = 0; i < mHeaderPositions.length; i++) {
			sections.add(new Section(mHeaderPositions[i], mHeaderNames[i]));
		}
		SimpleSectionedGridAdapter simpleSectionedGridAdapter = new SimpleSectionedGridAdapter(
				this, adapter, R.layout.grid_item_header, R.id.header_layout,
				R.id.header);

		simpleSectionedGridAdapter.setGridView(photoGridView);
		simpleSectionedGridAdapter
				.setSections(sections.toArray(new Section[0]));
		photoGridView.setAdapter(simpleSectionedGridAdapter);
	}

	private String camFilePath = ""; // 临时存放照片路径
	int galleryCnt = 0;
	boolean enableRefresh = false;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case SHOPPINGORDER:
				final int cnt = new DatabaseHelper(MainActivity.this)
						.getCartCount();
				// tvCartCnt.setText("" + cnt);
				enableRefresh = true;
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							Thread.sleep(1000);
							Message message = new Message();
							message.obj = "" + cnt;
							message.what = UPDATECART;
							handler.sendMessage(message);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}).start();
				break;
			case CAM:
				if (camFilePath.length() > 0) {
					MediaScannerConnection
							.scanFile(
									this,
									new String[] { camFilePath },
									null,
									new MediaScannerConnection.OnScanCompletedListener() {
										public void onScanCompleted(
												String path, Uri uri) {
											Log.i("ExternalStorage", "Scanned "
													+ path + ":");
											Log.i("ExternalStorage", "-> uri="
													+ uri);
											if (galleryCnt > 0
													&& Util.getGalleryCount(MainActivity.this)
															- galleryCnt > 1) {
												Util.deleteAlbumFile(MainActivity.this);
												// getContentResolver().delete(uri,
												// null,
												// null);
											}
											startRefreshPhotos();
										}
									});
				}
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void initMainView() {
		tvCartCnt = (TextView) findViewById(R.id.tv_cartcnt);
		iv_icon = (ImageView) findViewById(R.id.iv_icon);
		iv_bottom = (CircleImageView) findViewById(R.id.iv_bottom);
		photoGridView = (GridView) findViewById(R.id.gv_img);
		tv_noimg = (TextView) findViewById(R.id.iv_noimg);
		iv_info = (TextView) findViewById(R.id.iv_info);
		iv_cam = (ImageView) findViewById(R.id.iv_cam);
		iv_cam.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				galleryCnt = Util.getGalleryCount(MainActivity.this);
				File root = Environment
						.getExternalStoragePublicDirectory("photoprint");
				if (!root.exists()) {
					root.mkdirs();
				}
				DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss",
						Locale.CHINA);
				String fileName = format.format(new Date()) + ".jpg";
				File f = new File(root, fileName);
				camFilePath = root + File.separator + fileName;
				Intent intent = new Intent(); // 调用照相机
				intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
				startActivityForResult(intent, CAM);
				// startActivity(intent); // Samsung will not save to the system
				// album
			}
		});
		iv_select = (ImageView) findViewById(R.id.iv_select);
		iv_select.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String selected = adapter.getCheckedItems();
				if (selected.length() > 0) {
					Intent intent = new Intent(MainActivity.this,
							ImageActivity.class);
					intent.putExtra("path", selected);
					startActivityForResult(intent, SHOPPINGORDER);
					// startActivity(intent);
				} else {
					ToastUtil.showTips(MainActivity.this,
							R.drawable.tips_error, "您好像没有选择要打印的照片");
				}
			}
		});
		// photoGridView.setFastScrollEnabled(true);
		// adapter = new MyImageAdapter(this);
		// photoGridView.setAdapter(adapter);
		// photoGridView.setOnItemClickListener(new OnItemClickListener() {
		// @Override
		// public void onItemClick(AdapterView<?> parent, View view,
		// int position, long id) {
		// Intent intent = new Intent(MainActivity.this,
		// ImageActivity.class);
		// intent.putExtra("path", adapter.getItem(position));
		// startActivity(intent);
		// }
		// });
		lvMenu = (ListView) findViewById(R.id.lvmenu);
		lvMenu.setAdapter(new MenuAdapter(MainActivity.this, initMenu()));
		lvMenu.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Intent intent = null;
				switch (position) {
				case 2:
					intent = new Intent(MainActivity.this, MapActivity.class);
					startActivity(intent);
					break;
				case 1:
					intent = new Intent(MainActivity.this,
							ShoppingOrderActivity.class);
					startActivity(intent);
					break;
				case 0:
					intent = new Intent(MainActivity.this,
							ShoppingOrderActivity.class);
					startActivity(intent);
					break;
				case 3:
					intent = new Intent(MainActivity.this,
							FavouritesActivity.class);
					startActivity(intent);
					break;
				default:
					Toast.makeText(getApplicationContext(),
							"click " + position, Toast.LENGTH_SHORT).show();
					break;
				}
			}
		});
		iv_icon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dragLayout.open();
			}
		});

		int cnt = new DatabaseHelper(MainActivity.this).getCartCount();
		tvCartCnt.setText("" + cnt);
		btCart = (ImageButton) findViewById(R.id.bt_cart);
		btCart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						ShoppingCartActivity.class);
				// startActivity(intent);
				startActivityForResult(intent, SHOPPINGORDER);
			}
		});
		tv_login = (TextView) findViewById(R.id.tv_login);
		tv_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						LoginActivity.class);
				startActivity(intent);
			}
		});
		tv_setting = (TextView) findViewById(R.id.tv_setting);
		tv_setting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						SettingActivity.class);
				startActivity(intent);
			}
		});
	}

	private ArrayList<MenuItem> initMenu() {
		ArrayList<MenuItem> menuItems = new ArrayList<MenuItem>();
		MenuItem menuItem = new MenuItem();
		menuItem.setNumber(2);
		menuItem.setText("我的订单");
		menuItems.add(menuItem);
		menuItem = new MenuItem();
		menuItem.setNumber(0);
		menuItem.setText("交易记录");
		menuItems.add(menuItem);
		menuItem = new MenuItem();
		menuItem.setNumber(0);
		menuItem.setText("网点查询");
		menuItems.add(menuItem);
		menuItem = new MenuItem();
		menuItem.setNumber(0);
		menuItem.setText("我的收藏");
		menuItems.add(menuItem);
		menuItem = new MenuItem();
		menuItem.setNumber(0);
		menuItem.setText("个人信息");
		menuItems.add(menuItem);
		menuItem = new MenuItem();
		menuItem.setNumber(0);
		menuItem.setText("退出");
		menuItems.add(menuItem);
		return menuItems;
	}

	Dialog dlg;

	@Override
	public void onBackPressed() {
		if (dragLayout.isMenuOpened()) {
			dragLayout.close(true);
			return;
		}
		OnClickListener confirmListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (null != dlg) {
					dlg.dismiss();
				}
				finish();
			}
		};
		if (null == dlg)
			dlg = DialogUtil.getConfirmDialog(this, "确认离开印客？",
					confirmListener);
		dlg.show();
	}

	@Override
	public void onPause() {
		super.onPause();
		galleryCnt = Util.getGalleryCount(MainActivity.this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (galleryCnt > 0
				&& Util.getGalleryCount(MainActivity.this) > galleryCnt) {
			startRefreshPhotos();
		}
	}

	private String getCheckedItems(GridView gridView) {
		String rtStr = "";
		for (int i = 0; i < gridView.getChildCount(); i++) {
			CheckBox checkBox = (CheckBox) gridView.getChildAt(i).findViewById(
					R.id.ck_item);
			if (null != checkBox && checkBox.isChecked()) {
				TextView path = (TextView) gridView.getChildAt(i).findViewById(
						R.id.tv_path);
				rtStr += "," + path.getText().toString();
			}
		}
		return rtStr.length() > 1 ? rtStr.substring(1) : "";
	}

	@SuppressWarnings("unchecked")
	private void loadImage() {
		Map<String, Object> rtMap = Util.getGalleryPhotos(this);
		ArrayList<PhotoCheckItem> photos = (ArrayList<PhotoCheckItem>) rtMap
				.get("photos");
		Map<String, Integer> sections = (Map<String, Integer>) rtMap
				.get("sections");
		if (photos.size() > 0) {
			Iterator<String> iterator = sections.keySet().iterator();
			mHeaderNames = new String[sections.keySet().size()];
			mHeaderPositions = new Integer[sections.keySet().size()];
			int i = 0, previousValue = 0;
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				mHeaderNames[i] = key;
				if (0 == i) {
					mHeaderPositions[i] = 0;
					previousValue = sections.get(key);
				} else {
					mHeaderPositions[i] = mHeaderPositions[i - 1]
							+ previousValue;
					previousValue = sections.get(key);
				}
				i++;
			}
			Message message = new Message();
			message.obj = photos;
			message.what = LOADOK;
			handler.sendMessage(message);
		} else {
			handler.sendEmptyMessage(LOADFAIL);
		}
	}

	static class MyHandler extends Handler {

		WeakReference<MainActivity> context;

		public MyHandler(MainActivity context) {
			this.context = new WeakReference<MainActivity>(context);
		}

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			final MainActivity activity = context.get();
			switch (msg.what) {
			case LOADOK:
				ArrayList<PhotoCheckItem> photos = (ArrayList<PhotoCheckItem>) msg.obj;
				activity.tv_noimg.setVisibility(View.GONE);
				activity.iv_info.setVisibility(View.GONE);
				activity.adapter.addAll(photos);
				activity.refreshPhotos();
				activity.tv_noimg.setVisibility(View.GONE);
				String s = "file://"
						+ ((PhotoCheckItem) activity.adapter.getItem(0))
								.getPath();
				ImageLoader.getInstance().displayImage(s, activity.iv_icon);
				ImageLoader.getInstance().displayImage(s, activity.iv_bottom);
				activity.iv_icon.startAnimation(AnimationUtils.loadAnimation(
						activity, R.anim.shake));
				break;
			case LOADFAIL:
				activity.tv_noimg.setVisibility(View.VISIBLE);
				activity.iv_info.setVisibility(View.GONE);
				break;
			case UPDATECART:
				final String cnt = (String) msg.obj;
				RotateAnimation rotateAnim = null;
				float cX = activity.tvCartCnt.getWidth() / 2.0f;
				float cY = activity.tvCartCnt.getHeight() / 2.0f;
				rotateAnim = new RotateAnimation(cX, cY,
						RotateAnimation.ROTATE_DECREASE);
				rotateAnim
						.setInterpolatedTimeListener(new InterpolatedTimeListener() {

							@Override
							public void interpolatedTime(float interpolatedTime) {
								if (activity.enableRefresh
										&& interpolatedTime > 0.5f) {
									activity.tvCartCnt.setText(cnt);
									activity.enableRefresh = false;
								}
							}
						});
				rotateAnim.setFillAfter(true);
				activity.tvCartCnt.startAnimation(rotateAnim);
				break;
			}
			super.handleMessage(msg);
		}
	}
}
